<template>
  <view class="permission-center">
    <view class="fix-top-window">
      <view class="uni-header">
        <view class="uni-group">
          <button
            class="uni-button"
            type="success"
            size="mini"
            @click="useTemplate"
          >
            使用模板
          </button>
          <button
            v-if="currentTab === 'menu'"
            class="uni-button"
            type="warn"
            size="mini"
            @click="hideDuplicateMenus"
          >
            隐藏重复菜单
          </button>
          <input
            class="uni-search"
            type="text"
            v-model="globalQuery"
            @confirm="globalSearch"
            :placeholder="'搜索' + currentTabName"
          />
          <button
            class="uni-button hide-on-phone"
            type="default"
            size="mini"
            @click="globalSearch"
          >
            搜索
          </button>
        </view>
      </view>

      <!-- 标签页切换 -->
      <view class="uni-tabs__header">
        <view class="uni-tabs__nav-wrap">
          <view class="uni-tabs__nav-scroll">
            <view class="uni-tabs__nav">
              <view
                v-for="(tab, index) in tabs || []"
                :key="tab ? tab.key : index"
                @click="tab && switchTab(tab.key)"
                :class="{ 'is-active': tab && currentTab === tab.key }"
                class="uni-tabs__item"
              >
                {{ tab ? tab.name : "" }}
              </view>
            </view>
          </view>
        </view>
      </view>

      <!-- 动态生成各个模块 -->
      <template v-for="(tab, index) in tabs || []" :key="tab ? tab.key : index">
        <view v-if="tab && currentTab === tab.key" class="tab-content">
          <view
            class="uni-header"
            style="border-bottom: 0; margin-bottom: -15px"
          >
            <view class="uni-group">
              <button
                class="uni-button"
                type="primary"
                size="mini"
                @click="openAddDialog(tab.key)"
              >
                新增{{ tab.name ? tab.name.replace("管理", "") : "" }}
              </button>
              <button
                v-if="getConfig(tab.key).supportBatchDelete"
                class="uni-button"
                type="warn"
                size="mini"
                :disabled="
                  !getSelectedIds(tab.key) ||
                  getSelectedIds(tab.key).length === 0
                "
                @click="batchDelete(tab.key)"
              >
                批量删除
              </button>
            </view>
          </view>
          <view class="uni-container">
            <unicloud-db
              v-if="getCollection(tab.key)"
              :ref="tab.key + 'Udb'"
              :collection="getCollection(tab.key)"
              :field="getField(tab.key)"
              :where="getWhere(tab.key)"
              page-data="replace"
              :orderby="getConfig(tab.key).orderby"
              :getcount="true"
              :page-size="getConfig(tab.key).pageSize"
              :page-current="getPageCurrent(tab.key)"
              v-slot:default="{ data, pagination, loading, error }"
              loadtime="manual"
              @load="onDataLoad(tab.key, $event)"
            >
              <uni-table
                :ref="tab.key + 'Table'"
                :loading="loading"
                :emptyText="error.message || '暂无数据'"
                border
                stripe
                :type="getConfig(tab.key).supportBatchDelete ? 'selection' : ''"
                @selection-change="onSelectionChange(tab.key, $event)"
              >
                <uni-tr>
                  <uni-th
                    v-for="col in getConfig(tab.key).tableColumns || []"
                    :key="col.key"
                    :align="col.align || 'center'"
                    :width="col.width"
                  >
                    {{ col.label }}
                  </uni-th>
                  <uni-th align="center" width="150">操作</uni-th>
                </uni-tr>
                <uni-tr
                  v-for="(item, itemIndex) in getList(tab.key)"
                  :key="itemIndex"
                >
                  <uni-td
                    v-for="col in getConfig(tab.key).tableColumns || []"
                    :key="col.key"
                    :align="col.align || 'center'"
                    :class="getCellClass(col, item)"
                  >
                    <!-- 日期类型 -->
                    <template v-if="col.type === 'date'">
                      <uni-dateformat
                        :threshold="[0, 0]"
                        :date="item[col.key]"
                      ></uni-dateformat>
                    </template>
                    <!-- 标签类型 -->
                    <template v-else-if="col.type === 'tags'">
                      <view
                        :class="
                          col.tagType === 'primary'
                            ? 'permission-tags'
                            : 'role-tags'
                        "
                      >
                        <uni-tag
                          v-for="tag in item[col.key] || []"
                          :key="tag"
                          :type="col.tagType || 'primary'"
                          size="small"
                          :text="tag"
                          style="margin: 2px"
                        ></uni-tag>
                        <text
                          v-if="
                            !item[col.key] ||
                            !Array.isArray(item[col.key]) ||
                            item[col.key].length === 0
                          "
                          class="empty-text"
                        >
                          {{
                            col.tagType === "primary" ? "暂无权限" : "暂无角色"
                          }}
                        </text>
                      </view>
                    </template>
                    <!-- 状态类型 -->
                    <template v-else-if="col.type === 'status'">
                      <text :class="{ 'status-disabled': item[col.key] === 1 }">
                        {{
                          col.statusMap && col.statusMap[item[col.key]]
                            ? col.statusMap[item[col.key]]
                            : item[col.key]
                        }}
                      </text>
                    </template>
                    <!-- 开关类型 -->
                    <template v-else-if="col.type === 'switch'">
                      <switch
                        :checked="item[col.key]"
                        @change="toggleSwitch(tab.key, item, col.key)"
                      />
                    </template>
                    <!-- 普通文本 -->
                    <template v-else>
                      {{
                        col.formatter
                          ? col.formatter(item[col.key])
                          : item[col.key]
                      }}
                    </template>
                  </uni-td>
                  <uni-td align="center">
                    <view class="uni-group">
                      <button
                        @click="editItem(tab.key, item)"
                        class="uni-button"
                        size="mini"
                        type="primary"
                      >
                        编辑
                      </button>
                      <button
                        v-if="canDelete(tab.key, item)"
                        @click="deleteItem(tab.key, item._id)"
                        class="uni-button"
                        size="mini"
                        type="warn"
                      >
                        删除
                      </button>
                    </view>
                  </uni-td>
                </uni-tr>
              </uni-table>
              <view
                v-if="getConfig(tab.key).pageSize < 20000"
                class="uni-pagination-box"
              >
                <uni-pagination
                  show-icon
                  show-page-size
                  :page-size="pagination.size"
                  v-model="pagination.current"
                  :total="pagination.count"
                  @change="onPageChanged(tab.key, $event)"
                />
              </view>
            </unicloud-db>
          </view>
        </view>
      </template>
    </view>

    <!-- 新增/编辑对话框 -->
    <uni-popup ref="addDialog" type="center" :mask-click="false">
      <view class="dialog-container">
        <view class="dialog-header">
          <text class="dialog-title">{{ dialogTitle }}</text>
          <text class="dialog-close" @click="closeDialog">✕</text>
        </view>
        <view class="dialog-content">
          <view v-if="dialogType" class="form-container">
            <uni-forms
              :ref="dialogType + 'Form'"
              :model="getFormData(dialogType)"
              :rules="getFormRules(dialogType)"
              label-width="100px"
            >
              <uni-forms-item
                v-for="field in getConfig(dialogType).formFields || []"
                :key="field.key"
                :name="field.key"
                :label="field.label"
                :required="field.required"
                v-show="!field.show || field.show(getFormData(dialogType))"
              >
                <!-- 输入框 -->
                <uni-easyinput
                  v-if="field.type === 'input'"
                  v-model="getFormData(dialogType)[field.key]"
                  :placeholder="field.placeholder"
                  :disabled="
                    field.disabled && field.disabled(getFormData(dialogType))
                  "
                />
                <!-- 文本域 -->
                <uni-easyinput
                  v-else-if="field.type === 'textarea'"
                  type="textarea"
                  v-model="getFormData(dialogType)[field.key]"
                  :placeholder="field.placeholder"
                />
                <!-- 数字输入 -->
                <uni-easyinput
                  v-else-if="field.type === 'number'"
                  type="number"
                  v-model="getFormData(dialogType)[field.key]"
                  :placeholder="field.placeholder"
                />
                <!-- 多选框 -->
                <view v-else-if="field.type === 'checkbox'" class="checkbox-container">
                  <uni-data-checkbox
                    v-if="field.collection"
                    :multiple="field.multiple !== false"
                    v-model="getFormData(dialogType)[field.key]"
                    :collection="field.collection"
                    :page-size="500"
                    :field="field.field"
                  />
                </view>
                <!-- 下拉选择 -->
                <uni-data-select
                  v-else-if="field.type === 'select'"
                  v-if="field.collection"
                  v-model="getFormData(dialogType)[field.key]"
                  :collection="field.collection"
                  :page-size="500"
                  :field="field.field"
                  :clearable="field.clearable"
                />
                <!-- 开关 -->
                <switch
                  v-else-if="field.type === 'switch'"
                  :checked="getSwitchValue(dialogType, field)"
                  @change="bindSwitch(dialogType, field, $event.detail.value)"
                />
              </uni-forms-item>
            </uni-forms>
          </view>

          <view class="dialog-buttons">
            <button class="uni-button" type="primary" @click="saveItem">
              保存
            </button>
            <button class="uni-button" type="default" @click="closeDialog">
              取消
            </button>
          </view>
        </view>
      </view>
    </uni-popup>

  </view>
</template>

<script>
import { moduleConfig, tabs } from "./config.js";
import { templateData } from "./template.js";
const db = uniCloud.database();

export default {
  data() {
    // 确保 tabs 存在，如果导入失败则使用默认值
    const tabsList = tabs || [
      { key: "permission", name: "权限管理" },
      { key: "role", name: "角色管理" },
      { key: "user", name: "用户管理" },
      { key: "menu", name: "菜单管理" },
    ];

    // 动态初始化数据
    const data = {
      currentTab: "user",
      tabs: tabsList,
      globalQuery: "",
      dialogType: "",
      dialogTitle: "",
    };

    // 为每个模块初始化数据
    if (Array.isArray(tabsList)) {
      tabsList.forEach((tab) => {
        if (tab && tab.key) {
          const config =
            moduleConfig && moduleConfig[tab.key] ? moduleConfig[tab.key] : {};
          data[tab.key + "List"] = [];
          data[tab.key + "Where"] = "";
          data[tab.key + "PageCurrent"] = 1;
          data[tab.key + "FormData"] = {};
          data[
            "selected" +
              tab.key.charAt(0).toUpperCase() +
              tab.key.slice(1) +
              "Ids"
          ] = [];
        }
      });
    }

    return data;
  },
  computed: {
    currentTabName() {
      const tab = this.tabs.find((t) => t.key === this.currentTab);
      return tab ? tab.name : "";
    },
  },
  onLoad() {
    this.loadData();
  },
  methods: {
    // 获取模块配置
    getConfig(type) {
      return moduleConfig[type] || {};
    },
    // 获取集合（用于查询）
    getCollection(type) {
      const config = this.getConfig(type);
      const collection = config.collection;
      // 如果collection为undefined或null，返回空字符串避免错误
      if (!collection) {
        console.warn(`Collection not found for type: ${type}`);
        return '';
      }
      return collection;
    },
    // 获取实际集合名（用于增删改）
    getCollectionName(type) {
      const config = this.getConfig(type);
      if (Array.isArray(config.collection)) {
        // 联表查询时，取第一个集合名
        const firstCollection = config.collection[0];
        if (firstCollection && firstCollection.collection) {
          return firstCollection.collection;
        }
        // 如果是getTemp()的结果，需要从配置中推断
        if (type === "role") {
          return "uni-id-roles";
        } else if (type === "user") {
          return "uni-id-users";
        }
        return "opendb-admin-menus";
      }
      // 如果collection为字符串，直接返回
      if (typeof config.collection === 'string') {
        return config.collection;
      }
      // 如果collection为undefined或null，根据type推断
      if (!config.collection) {
        console.warn(`Collection name not found for type: ${type}, using fallback`);
        // 根据type返回默认集合名
        const fallbackMap = {
          'permission': 'uni-id-permissions',
          'role': 'uni-id-roles',
          'user': 'uni-id-users',
          'menu': 'opendb-admin-menus'
        };
        return fallbackMap[type] || '';
      }
      return config.collection;
    },
    // 获取字段
    getField(type) {
      const config = this.getConfig(type);
      // 如果是数组（联表查询），field 已经在 getTemp() 中指定，不需要再传递
      if (Array.isArray(config.collection)) {
        return undefined; // 联表查询时不传递 field
      }
      // 如果field为undefined，返回undefined而不是null
      return config.field || undefined;
    },
    // 获取查询条件
    getWhere(type) {
      return this[type + "Where"];
    },
    // 获取当前页码
    getPageCurrent(type) {
      return this[type + "PageCurrent"];
    },
    // 获取列表数据
    getList(type) {
      return this[type + "List"] || [];
    },
    // 获取表单数据
    getFormData(type) {
      return this[type + "FormData"] || {};
    },
    // 获取表单验证规则
    getFormRules(type) {
      const config = this.getConfig(type);
      const rules = {};
      if (config && config.formFields && Array.isArray(config.formFields)) {
        config.formFields.forEach((field) => {
          if (field && field.required) {
            rules[field.key] = {
              rules: [{ required: true, errorMessage: `请输入${field.label}` }],
            };
          }
        });
      }
      return rules;
    },
    // 获取选中的ID列表
    getSelectedIds(type) {
      const key =
        "selected" + type.charAt(0).toUpperCase() + type.slice(1) + "Ids";
      return this[key] || [];
    },
    // 获取单元格样式类
    getCellClass(col, item) {
      if (col.type === "status" && item[col.key] === 1) {
        return "status-disabled";
      }
      if (col.type === "switch" && !item[col.key]) {
        return "menu-disable";
      }
      return "";
    },
    // 是否可以删除
    canDelete(type, item) {
      if (type === "menu") {
        return (
          item.menu_id !== "system_menu" && item.menu_id !== "system_management"
        );
      }
      return true;
    },
    // 获取开关值
    getSwitchValue(type, field) {
      const formData = this.getFormData(type);
      if (field.valueMap) {
        return formData[field.key] === field.valueMap.true;
      }
      return formData[field.key];
    },
    // 绑定开关值
    bindSwitch(type, field, value) {
      const formData = this.getFormData(type);
      if (field.valueMap) {
        formData[field.key] = value
          ? field.valueMap.true
          : field.valueMap.false;
      } else {
        formData[field.key] = value;
      }
    },
    // 切换开关
    toggleSwitch(type, item, key) {
      item[key] = !item[key];
      const collectionName = this.getCollectionName(type);
      db.collection(collectionName)
        .doc(item._id)
        .update({
          [key]: item[key],
        })
        .catch((e) => {
          uni.showToast({ title: e.message || "操作失败", icon: "none" });
          item[key] = !item[key];
        });
    },
    switchTab(tab) {
      this.currentTab = tab;
      this.globalQuery = "";
      this.loadData();
    },
    globalSearch() {
      const query = this.globalQuery.trim();
      if (!query) {
        this.loadData();
        return;
      }
      const config = this.getConfig(this.currentTab);
      const queryRe = new RegExp(query, "i");
      const conditions = config.searchFields.map((field) => ({
        [field]: queryRe,
      }));
      this[this.currentTab + "Where"] = db.command.or(conditions);
      const udbRef = this.getUdbRef(this.currentTab);
      if (udbRef && typeof udbRef.loadData === "function") {
        udbRef.loadData();
      }
    },
    // 获取UDB组件引用（处理v-for导致的数组情况）
    getUdbRef(type) {
      const ref = this.$refs[type + "Udb"];
      if (Array.isArray(ref)) {
        return ref[0];
      }
      return ref;
    },
    loadData() {
      this.$nextTick(() => {
        // 延迟一下确保组件已渲染
        setTimeout(() => {
          const udbRef = this.getUdbRef(this.currentTab);
          if (udbRef && typeof udbRef.loadData === "function") {
            udbRef.loadData();
          } else {
            console.warn(
              "UDB ref not found or loadData not available:",
              this.currentTab,
              udbRef
            );
          }
        }, 100);
      });
    },
    onDataLoad(type, data) {
      const config = this.getConfig(type);
      let processedData = data;
      if (config.afterLoad) {
        processedData = config.afterLoad(data);
      }
      this[type + "List"] = processedData;
    },
    onSelectionChange(type, e) {
      const list = this.getList(type);
      const key =
        "selected" + type.charAt(0).toUpperCase() + type.slice(1) + "Ids";
      this[key] = e.detail.index.map((i) => list[i]._id);
    },
    onPageChanged(type, e) {
      this[type + "PageCurrent"] = e.current;
      const udbRef = this.getUdbRef(type);
      if (udbRef && typeof udbRef.loadData === "function") {
        udbRef.loadData({ current: e.current });
      }
    },
    openAddDialog(type) {
      this.dialogType = type;
      const config = this.getConfig(type);
      this.dialogTitle = "新增" + config.name.replace("管理", "");
      this[type + "FormData"] = { ...config.defaultFormData };
      this.$refs.addDialog.open();
    },
    editItem(type, item) {
      this.dialogType = type;
      const config = this.getConfig(type);
      this.dialogTitle = "编辑" + config.name.replace("管理", "");

      // 复制item，恢复原始名称（如果是菜单）
      let formData = { ...item };

      // 如果是用户，删除敏感字段（避免权限校验错误）
      if (type === "user") {
        const sensitiveFields = [
          "password",
          "token",
          "dcloud_appid",
          "wx_unionid",
          "wx_openid",
          "qq_openid",
          "ali_openid",
          "baidu_openid",
          "toutiao_openid",
        ];
        sensitiveFields.forEach((field) => {
          if (formData[field] !== undefined) {
            delete formData[field];
          }
        });
      }

      if (type === "menu" && item._originalName) {
        formData.name = item._originalName;
      }

      if (config.formDataTransform && config.formDataTransform.edit) {
        formData = config.formDataTransform.edit(formData);
      }
      this[type + "FormData"] = formData;
      this.$refs.addDialog.open();
    },
    closeDialog() {
      this.$refs.addDialog.close();
    },
    async saveItem() {
      try {
        const type = this.dialogType;
        const config = this.getConfig(type);
        const formRef = this.$refs[type + "Form"];

        // 表单验证
        if (formRef) {
          await formRef.validate();
        }

        const formData = this.getFormData(type);
        const data = { ...formData };
        const isEdit = !!data._id;

        // 保存前处理
        let saveData = data;
        let useUniId = false;
        if (config.beforeSave) {
          const result = await config.beforeSave(data, isEdit);
          if (result && result.data) {
            saveData = result.data;
            useUniId = result.useUniId || false;
          }
        }

        // 获取集合
        const collectionName = this.getCollectionName(type);
        if (!collectionName) {
          uni.showToast({ title: "集合名不能为空", icon: "none" });
          return;
        }
        const collection = db.collection(collectionName);
        if (!collection) {
          uni.showToast({ title: "集合对象创建失败", icon: "none" });
          return;
        }

         // 如果是角色，需要处理菜单配置
         let menuIds = null;
         if (type === "role" && saveData.menu) {
           menuIds = saveData.menu;
           // 从保存数据中移除menu字段（因为角色表可能不支持该字段）
           delete saveData.menu;
         }

        if (isEdit) {
          // 编辑
          const id = saveData._id;
          delete saveData._id;
          await collection.doc(id).update(saveData);
        } else {
          // 新增
          if (useUniId) {
            // 使用 uni-id 创建用户
            const uniID = uniCloud.importObject("uni-id-co");
            const createRes = await uniID.createUser(saveData);
            if (createRes.code !== 0) {
              uni.showToast({
                title: createRes.msg || "创建失败",
                icon: "none",
              });
              return;
            }
          } else {
            delete saveData._id;
            await collection.add(saveData);
          }
        }

         // 如果是角色且有菜单配置，更新菜单权限
         if (type === "role" && menuIds && Array.isArray(menuIds) && menuIds.length > 0) {
           try {
             // 获取角色的权限
             const rolePermissions = saveData.permission || [];
             const permissionIds = rolePermissions.map(p => typeof p === 'string' ? p : p.permission_id);
             
             // 获取角色ID（编辑时使用_id，新增时从返回结果获取）
             let roleIdForMenu = null;
             if (isEdit) {
               roleIdForMenu = data._id;
             } else {
               // 新增时，需要查询刚创建的角色
               if (collection && saveData.role_id) {
                 const roleRes = await collection.where({ role_id: saveData.role_id }).get();
                 if (roleRes.data && roleRes.data.length > 0) {
                   roleIdForMenu = roleRes.data[0]._id;
                 }
               }
             }
             
             // 尝试更新角色的menu字段
             if (roleIdForMenu) {
               try {
                 await collection.doc(roleIdForMenu).update({ menu: menuIds });
               } catch (e) {
                 console.log("角色表不支持menu字段");
               }
             }
             
             // 更新菜单的permission字段
             const menuCollection = db.collection("opendb-admin-menus");
             const allMenusRes = await menuCollection.get();
             const allMenus = allMenusRes.data || [];
             
             for (let i = 0; i < menuIds.length; i++) {
               const menuId = menuIds[i];
               const menu = allMenus.find(m => m.menu_id === menuId);
               if (menu) {
                 const currentPermissions = menu.permission || [];
                 const mergedPermissions = [...new Set([...currentPermissions, ...permissionIds])];
                 await menuCollection.doc(menu._id).update({
                   permission: mergedPermissions,
                 });
               }
             }
           } catch (e) {
             console.error("更新菜单权限失败:", e);
           }
         }

        uni.showToast({ title: "保存成功", icon: "success" });
        this.closeDialog();
        this.loadData();
      } catch (e) {
        console.error(e);
        uni.showToast({ title: e.message || "保存失败", icon: "none" });
      }
    },
    deleteItem(type, id) {
      uni.showModal({
        title: "提示",
        content: "确定要删除吗？",
        success: async (res) => {
          if (res.confirm) {
            try {
              const config = this.getConfig(type);

              // 删除前检查
              if (config.beforeDelete) {
                await config.beforeDelete(id);
              }

              // 获取集合
              const collectionName = this.getCollectionName(type);
              const collection = db.collection(collectionName);

              await collection.doc(id).remove();
              uni.showToast({ title: "删除成功", icon: "success" });
              this.loadData();
            } catch (e) {
              uni.showToast({ title: e.message || "删除失败", icon: "none" });
            }
          }
        },
      });
    },
    batchDelete(type) {
      const ids = this.getSelectedIds(type);
      if (!ids.length) return;

      uni.showModal({
        title: "提示",
        content: `确定要删除选中的 ${ids.length} 项吗？`,
        success: async (res) => {
          if (res.confirm) {
            try {
              const collectionName = this.getCollectionName(type);
              const collection = db.collection(collectionName);

              await collection.where({ _id: db.command.in(ids) }).remove();
              uni.showToast({ title: "删除成功", icon: "success" });
              this.loadData();
            } catch (e) {
              uni.showToast({ title: e.message || "删除失败", icon: "none" });
            }
          }
        },
      });
    },
    // 使用模板生成预设数据
    async useTemplate() {
      uni.showModal({
        title: "使用模板",
        content:
          "使用模板将自动生成预设的权限、角色、用户、菜单数据。是否继续？",
        success: async (res) => {
          if (res.confirm) {
            try {
              uni.showLoading({ title: "正在生成模板数据..." });

              // 1. 生成权限
              await this.importPermissions();

              // 2. 生成角色
              await this.importRoles();

              // 3. 生成用户
              await this.importUsers();

              // 4. 生成菜单
              await this.importMenus();

              uni.hideLoading();
              uni.showToast({
                title: "模板数据生成成功！",
                icon: "success",
                duration: 2000,
              });

              // 强制刷新所有标签页的数据
              this.$nextTick(() => {
                // 刷新所有标签页的数据
                if (this.tabs && Array.isArray(this.tabs)) {
                  this.tabs.forEach((tab) => {
                    if (tab && tab.key) {
                      // 重置页码
                      this[tab.key + "PageCurrent"] = 1;
                      // 重置查询条件
                      this[tab.key + "Where"] = "";
                      // 刷新数据
                      const udbRef = this.getUdbRef(tab.key);
                      if (udbRef && typeof udbRef.loadData === "function") {
                        udbRef.loadData({ clear: true });
                      }
                    }
                  });
                }
                // 额外刷新当前标签页，确保立即显示
                setTimeout(() => {
                  const udbRef = this.getUdbRef(this.currentTab);
                  if (udbRef && typeof udbRef.loadData === "function") {
                    udbRef.loadData({ clear: true });
                  }
                }, 300);
              });
            } catch (e) {
              uni.hideLoading();
              uni.showToast({
                title: e.message || "模板生成失败",
                icon: "none",
                duration: 3000,
              });
            }
          }
        },
      });
    },
    // 导入权限
    async importPermissions() {
      if (
        !templateData ||
        !templateData.permissions ||
        !Array.isArray(templateData.permissions)
      ) {
        return;
      }
      const collection = db.collection("uni-id-permissions");
      for (let i = 0; i < templateData.permissions.length; i++) {
        const perm = templateData.permissions[i];
        // 检查是否已存在
        const exist = await collection
          .where({ permission_id: perm.permission_id })
          .get();
        if (
          exist &&
          exist.data &&
          Array.isArray(exist.data) &&
          exist.data.length === 0
        ) {
          await collection.add(perm);
        }
      }
    },
    // 导入角色
    async importRoles() {
      if (
        !templateData ||
        !templateData.roles ||
        !Array.isArray(templateData.roles)
      ) {
        return;
      }
      const collection = db.collection("uni-id-roles");
      for (let i = 0; i < templateData.roles.length; i++) {
        const role = templateData.roles[i];
        // 检查是否已存在
        const exist = await collection.where({ role_id: role.role_id }).get();
        if (
          exist &&
          exist.data &&
          Array.isArray(exist.data) &&
          exist.data.length === 0
        ) {
          await collection.add(role);
        }
      }
    },
    // 导入用户
    async importUsers() {
      if (
        !templateData ||
        !templateData.users ||
        !Array.isArray(templateData.users)
      ) {
        return;
      }
      const uniID = uniCloud.importObject("uni-id-co");
      for (let i = 0; i < templateData.users.length; i++) {
        const user = templateData.users[i];
        // 检查是否已存在（只查询 username 字段，避免权限校验错误）
        // JQL 语法：where 必须在 field 之前
        const exist = await db
          .collection("uni-id-users")
          .where({ username: user.username })
          .field({ username: true }) // 只查询 username 字段
          .get();
        if (
          exist &&
          exist.data &&
          Array.isArray(exist.data) &&
          exist.data.length === 0
        ) {
          const createRes = await uniID.createUser({
            username: user.username,
            password: user.password,
            nickname: user.nickname,
            mobile: user.mobile,
            email: user.email,
            role: user.role || [],
            status: user.status || 0,
          });
          if (createRes && createRes.code !== 0) {
            console.warn("创建用户失败:", user.username, createRes.msg);
          }
        }
      }
    },
    // 导入菜单
    async importMenus() {
      if (
        !templateData ||
        !templateData.menus ||
        !Array.isArray(templateData.menus)
      ) {
        return;
      }
      const collection = db.collection("opendb-admin-menus");
      for (let i = 0; i < templateData.menus.length; i++) {
        const menu = templateData.menus[i];
        // 检查是否已存在
        const exist = await collection.where({ menu_id: menu.menu_id }).get();
        if (
          exist &&
          exist.data &&
          Array.isArray(exist.data) &&
          exist.data.length === 0
        ) {
          await collection.add(menu);
        }
      }
    },
    // 隐藏重复的菜单项（用户管理、角色管理、权限管理、菜单管理）
    async hideDuplicateMenus() {
      uni.showModal({
        title: "隐藏重复菜单",
        content:
          '将禁用左侧菜单栏中的"用户管理"、"角色管理"、"权限管理"、"菜单管理"菜单项（这些功能已在权限配置中心中统一管理）。是否继续？',
        success: async (res) => {
          if (res.confirm) {
            try {
              uni.showLoading({ title: "正在处理..." });
              const collection = db.collection("opendb-admin-menus");
              // 需要禁用的菜单ID列表
              const menuIds = [
                "system_user",
                "system_role",
                "system_permission",
                "system_menu",
              ];
              // 批量更新，将这些菜单的 enable 设置为 false
              for (let i = 0; i < menuIds.length; i++) {
                const menuId = menuIds[i];
                await collection
                  .where({ menu_id: menuId })
                  .update({ enable: false });
              }
              uni.hideLoading();
              uni.showToast({
                title: "操作成功！",
                icon: "success",
                duration: 2000,
              });
              // 刷新菜单列表
              setTimeout(() => {
                this.loadData();
              }, 500);
            } catch (e) {
              uni.hideLoading();
              uni.showToast({
                title: e.message || "操作失败",
                icon: "none",
                duration: 3000,
              });
            }
          }
        },
      });
    },
   },
 };
</script>

<style lang="scss">
.permission-center {
  .tab-content {
    padding-top: 10px;
  }

  .permission-tags,
  .role-tags {
    display: flex;
    flex-wrap: wrap;
    justify-content: center;

    .empty-text {
      color: #999;
      font-size: 12px;
    }
  }

  .status-disabled {
    color: #f56c6c;
  }

  .menu-disable {
    color: #f56c6c;
  }

  .dialog-container {
    width: 600px;
    max-width: 90vw;
    max-height: 80vh;
    background: #fff;
    border-radius: 8px;
    overflow: hidden;
  }

  .dialog-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 20px;
    border-bottom: 1px solid #eee;

    .dialog-title {
      font-size: 18px;
      font-weight: bold;
    }

    .dialog-close {
      font-size: 24px;
      color: #999;
      cursor: pointer;
    }
  }

  .dialog-content {
    padding: 20px;
    max-height: 60vh;
    overflow-y: auto;
  }

  .form-container {
    padding: 10px 0;
  }

  .dialog-buttons {
    display: flex;
    justify-content: flex-end;
    gap: 10px;
    margin-top: 20px;
  }

  .menu-checkbox-container {
    max-height: 300px;
    overflow-y: auto;
  }

  .uni-form-item-tips {
    font-size: 12px;
    color: #999;
    margin-top: 5px;
    line-height: 1.5;
  }

  .checkbox-container {
    width: 100%;
  }
}
</style>
